package com.msos.dao.BQueryDao;

import com.msos.model.business.Business;
import com.msos.model.customer.Customer;
import com.msos.model.customer.Customer_Business;
import com.msos.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: BQueryDao
 * @Description: TODO
 * @Author: hsx
 * @Date: 2022/4/14 9:21
 * @Version: v1.0
 */
public class BQueryDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDs());

    public Business getBusiness(Integer bid) throws SQLException {
        return queryRunner.query("select * from business where bid=?",new BeanHandler<>(Business.class),bid);
    }

    public Integer deleteBusiness(String bid) throws SQLException {
        return queryRunner.update("delete from customer_business where bid=?",bid);
    }

    public List<Customer_Business> getBusinessId(Integer uid) throws SQLException {
        return queryRunner.query("select * from customer_business where uid=?",new BeanListHandler<>(Customer_Business.class),uid);
    }

    public List<Business> getAllBusinesses(List<Customer_Business> bids) throws SQLException {
        StringBuffer sql = new StringBuffer("select * from business");
        if (bids.size() != 0){
            sql.append(" where ");
            Object[] params = new Object[bids.size()];
            for (int i = 0; i < bids.size(); i++) {
                if (i == bids.size()-1){
                    sql.append("bid != ?");
                }else {
                    sql.append("bid != ? and ");
                }
                params[i] = bids.get(i).getBid();
            }
            return queryRunner.query(sql.toString(),new BeanListHandler<>(Business.class),params);
        }
        return queryRunner.query(sql.toString(),new BeanListHandler<>(Business.class));
    }

    public Integer addBusiness(String bid, Integer uid) throws SQLException {
        return queryRunner.update("insert into customer_business (uid,bid) values (?,?)",uid,bid);
    }
}
